package earthalbumext;

import java.io.IOException;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

@SuppressWarnings("serial")
public class earthalbumextServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
          throws IOException {
    resp.setContentType("text/xml");
    PrintWriter out = resp.getWriter();

    try {
      double lat = Double.parseDouble(req.getParameter("lat"));
      double lon = Double.parseDouble(req.getParameter("lon"));
      URL flickr_url = new URL(FlickrAPI.getFlickrPhotosSearchByLatLon(lat, lon));
      HttpURLConnection connection = (HttpURLConnection) flickr_url.openConnection();
      connection.setRequestMethod("GET");
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.connect();

      InputStream is = connection.getInputStream();
      int c;
      String flickrResponse = "";
      while (true) {
        c = is.read();
        if (c == -1) {
          break;
        } else {
          flickrResponse += (char) c;
        }
      }
      out.println(flickrResponse);
    }
    catch (Exception ex) {
      System.out.println("Got exception! " + ex.getMessage());
    }
    finally {
      out.close();
    }
  }
}
